import java.io.*;
import java.net.*;
import java.util.*;

public class Server implements Runnable {
	public static int PORT = 2346;
	ServerSocket serverSocket;
	String head;
	
	public class Client extends Thread{
		Socket client = null;
		BufferedReader in = null;
		OutputStream out = null;
		
		public Client(Socket c){
			this.client = c;
			try{
				in = new BufferedReader(new InputStreamReader(client.getInputStream()));
				out = client.getOutputStream();
			}
			catch(Exception e){
				e.printStackTrace();
			}
			if (in!=null&&out!=null){
				start();
			}
		}
		public void run(){
			StringBuffer request=new StringBuffer(80);
			try{
				while(true){
					int c = in.read();
					if (c=='\t'||c=='\n'||c==-1) {  
	                    			break;  
	                		}
					request.append((char)c);
				}
				// handle command
				String get=request.toString();  
	            		System.out.println(get);  
	            		StringTokenizer st=new StringTokenizer(get);  
	            		String method=st.nextToken();  
	            		FileInputStream fis = null;
				if(method.equals("GET")){
					String fileName=st.nextToken();
					fileName = "."+fileName;
					try{
						fis = new FileInputStream(fileName);
					}
					catch(Exception e){
						e.printStackTrace();
						return;
					}
	                		//String path = new File("."+fileName).getCanonicalPath();
					//DataInputStream inStream = new DataInputStream(new BufferedInputStream(new FileInputStream(path)));
					//out
					out.write(head.getBytes());
					byte[] buffer = new byte[1024];
					int bytes = 0;
					while((bytes = fis.read(buffer))!=-1){
						out.write(buffer,0,bytes);
					}
					out.flush();
					
					//while(inStream.available()!=0){
					//	out.write((char)inStream.readByte());
					//}
					out.close();
				}
			}
			catch(Exception e){
				e.printStackTrace();
			}
			finally{
				if(client!=null){
					try {
						client.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	public Server(){
		String header = "HTTP/1.0 200 OK\015\012" + 
				"Server: HTTPServer\015\012" + 
				"Content-type: image/jpeg\015\012\015\012" + 
				"";
		this.head = header;
		try{
			serverSocket = new ServerSocket(PORT);
		}
		catch(Exception e){
			System.out.println("Failed");
			System.exit(1);
		}
		if(serverSocket==null)
			System.exit(1);
		new Thread(this).start();
		System.out.println("Server start at PORT: "+PORT);
	}

	@Override
	public void run() {
		Socket client = null;
		while(true){
			try{
				client = serverSocket.accept();
				if (client != null){
					System.out.println("Connect to "+client);
					new Client(client);
				}
			}
			catch(Exception e){
				
			}
		}
	}
	
	public static void main(String[] args){
		new Server();
	}
}
